package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.New;
import cn.wolfcode.trip.base.query.NewQueryObject;
import cn.wolfcode.trip.base.service.INewService;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/new")
public class NewController {
    @Autowired
    private INewService newService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") NewQueryObject qo, Model model) {
        qo.setOrderBy("releaseTime desc");
        model.addAttribute("pageInfo", newService.query(qo));
        return "new/list";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(New entity, MultipartFile img) {
        //先处理上传图片的问题
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0) {
            //把图片上传到本地图库
            String url = UploadUtil.upload(img);
            //替换旧的图片地址
            entity.setCoverUrl(url);
        }
        newService.saveOrUpdate(entity);
        return "redirect:/new/list.do";
    }

    @RequestMapping(value = "/getContentById", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getContentById(Long id) {
        return newService.getContentById(id);
    }
}
